﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;
using System.IO;
using System.Data.OleDb;
using System.Linq.Expressions;

namespace SBACN.WebSite.Admin.GuildMsg
{
	public partial class MonthlyEventDown : BasePage
	{
		/// <summary>
		/// 系统字典类型
		/// </summary>
		public string SystemType
		{
			get
			{
				//if (ViewState["SystemType"] == null)
				//    return "00020003";//默认值
				//else
				//    return ViewState["SystemType"].ToString();
				return this.SystemCode;
			}
			private set
			{
				ViewState["SystemType"] = this.SystemCode; ;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!AdminBasePage.CheckCodeRight(AdminBasePage.AdminInfo, SystemType))
			{
				AdminBasePage.RedirectWithMessage(AdminDefaultPage, "您没有访问当前页面的权限,请与系统管理员联系!");
				return;
			}

			ExportToExcel();
		}

		public void ExportToExcel()
		{

			Expression<Func<TB_MonthlyEvents, bool>> f = (c => true);
			Expression<Func<TB_MonthlyEvents, DateTime>> order = (c => c.EventDate);
			var resultE = DAL.DALHelper.Instance.GetList<TB_MonthlyEvents, DateTime>(f, order, false);

			string strTmpFileName = "~/Template/月度大事记.xls";
			string strDownloadFileName = "~/Template/Down/月度大事记" + DateTime.Now.Ticks +".xls";
			File.Copy(Server.MapPath(strTmpFileName), Server.MapPath(strDownloadFileName), true);

			string strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strDownloadFileName) + ";Extended Properties='Excel 8.0;HDR=Yes'";

			using (OleDbConnection conn = new OleDbConnection(strExcelConn))
			{
				conn.Open();
				foreach (var l in resultE)
				{
					string insertcmd = " INSERT INTO [Sheet1$] (日期,事件) VALUES ('" + l.EventDate.ToString("yyyy-MM-dd") + "','" + l.Description + "') ";
					OleDbCommand excmd = new OleDbCommand(insertcmd, conn);
					excmd.ExecuteNonQuery();
				}
				conn.Close();
			}
			Response.Redirect(strDownloadFileName);
		}
	}
}